#ifndef __MY__BUFFER__
#define __MY__BUFFER__

#include "util.hpp"
#include <vector>
#include <cassert>
namespace mylog
{
    #define DEFAULT_BUFFER_SIZE (1024*1024*10)
    #define THRESHOLD_BUFFER_SIZE (1024*1024*100)
    #define INCREMENT_BUFFER_SIZE (1024*1024*50)
    
    class Buffer 
    {
    private:
        std::vector<char> _buffer;
        size_t _reader_idx;//当前可读数据的下标
        size_t _writer_idx;//当前可写数据的下标
    public:
        Buffer():_buffer(DEFAULT_BUFFER_SIZE), _reader_idx(0), _writer_idx(0)
        {}
        //向缓冲区写入位置
        void push(const char* data, size_t len)
        {
            //如果缓冲区剩余长度不够怎么办？
            //1.直接返回, 固定大小
            //2.动态扩容,主要用于性能的测试
            //if(len > writeAbleSize()) return;
            ensureEnoughSize(len);

            //1.向buffer写入数据
            std::copy(data, data + len, &_buffer[_writer_idx]);
            //2.更新写位置
            moveWriter(len);
        }
        //返回可读数据的起始地址
        const char* begin()
        {
            return &_buffer[_reader_idx];
        }
        //返回可读数据的长度
        size_t readAbleSize()
        {
            return (_writer_idx - _reader_idx);
        }
        //返回可写数据的长度
        size_t writeAbleSize()
        {
            return (_buffer.size() - _writer_idx);
        }
        //对读写指针进行向后偏移工作
        void moveReader(size_t len)
        {
            assert(_reader_idx + len <= _writer_idx);
            _reader_idx += len;
        }
        void moveWriter(size_t len)
        {
            assert(_writer_idx + len <= _buffer.size());
            _writer_idx += len;
        }
        //重置读写位置，初始化缓冲区
        void reset()
        {
            _writer_idx = 0;
            _reader_idx = 0;
        }
        //对Buffer实现交换操作   
        void swap(Buffer& buffer)
        {
            _buffer.swap(buffer._buffer);
            std::swap(_writer_idx, buffer._writer_idx);
            std::swap(_reader_idx, buffer._reader_idx);
        }
        //判断缓冲区是否为空
        bool empty()
        {
            return (_reader_idx == _writer_idx);
        }
    private:
        void ensureEnoughSize(size_t len)
        {
            if(len <= writeAbleSize())  return;
            size_t newsize = 0;
            if(_buffer.size() < THRESHOLD_BUFFER_SIZE)
            {
                newsize = _buffer.size() * 2 + len;
            }
            else 
            {
                newsize = _buffer.size() + INCREMENT_BUFFER_SIZE + len;
            }
            _buffer.resize(newsize);
        }
    };
}
#endif